package com.starblink.store.view

import android.content.Context
import android.util.AttributeSet
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.postDelayed
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.load.DecodeFormat
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.ext.load
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.store.databinding.WidgetProductCardStoreDealsBinding

/**
 * 店铺折扣商品卡片View
 */
class ProductCardStoreDealsView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0,
) : LinearLayout(context, attrs, defStyleRes) {
    //===传参数据START
    lateinit var product: ProductF
    lateinit var activity: FragmentActivity
    var trackPage: Int = 0
    //===传参数据END

    // Widget视图
    val binding: WidgetProductCardStoreDealsBinding =
        WidgetProductCardStoreDealsBinding.inflate(inflater, this)
    init {
        // 使用ViewBinding.inflate方式添加Widget视图，root View的padding等属性会失效
        setPadding(8.dp, 8.dp, 8.dp, 12.dp)
        orientation = VERTICAL
    }

    /**
     * 商品卡片绑定数据
     */
    fun bindProduct(
        activity: FragmentActivity,
        product: ProductF, // 商品对象
        trackPage: Int, // 埋点页面
        position: Int // Item列表位置
    ) {
        this.product = product
        this.activity = activity
        this.trackPage = trackPage

        // 埋点：店铺详情-折扣好物Item
        trackData(
            page = SpmPageDef.StoreDetailPage,
            element = SpmElementDef.ELE_33009,
            params = mapOf(
                "merchantName" to (product.merchantWeb?.merchantName ?: ""),
                "index" to position.toString(),
                "productId" to (product.productId ?: ""),
                "standardSpuIds" to (product.standardSpuIds ?: ""),
            ),
            businessSuffixID = businessSuffixId(product)
        )

        //主图
        binding.ivProductPic.load(product.mainImg ?: "", format = DecodeFormat.PREFER_RGB_565)
//        ImageUtils.loadImage(mActivity, product.mainImg ?: "", 140.dp, 140.dp, binding.ivProduct)

        //主图-折扣标签
        binding.tvDiscountTag.visibleOrGone(
            product.disCountInfo?.discountPercent.isNullOrEmpty().not()
        ) {
            text = "-${product.disCountInfo?.discountPercent}"
        }

        // 价格
        binding.tvPrice.visibleOrGone(product.price != null) {
            show(
                product.price!!,
                product.currency,
                product.currencySymbol
            )
        }

        // 折扣价格
        binding.tvPriceOff.visibleOrGone(product.disCountInfo?.underlinePrice != null) {
            show(
                product.disCountInfo?.underlinePrice!!,
                product.currency,
                product.currencySymbol
            )
        }

        // 名字
        binding.tvName.text = product.title

        // 收藏按钮
        binding.ivCollect.run {
            updateCollect(product.collected)
            click { doCollectProduct() }
        }

        // 商品收藏事件处理
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == this.product.id) {
                    this.product.apolloValue("collected", event.collect)
                    updateCollect(this.product.collected)
                }
            }
        }
    }

    /**
     * 收藏商品
     */
    private fun doCollectProduct() {
        CommonMutateManage.collectProduct(
            ctx = context,
            id = product.id!!,
            type = product.type,
            scope = activity.lifecycleScope,
            collected = (product.collected == true),
            refreshState = {
                updateCollect(product.collected != true)
            }
        ) { it, collected ->
            if (it) {
                // 收藏或取消收藏成功，更新数据
                product.apolloValue("collected", collected)

                // 收藏成功，显示Add To Board提示(显示时隐藏收藏按钮)
                binding.layoutAddToBoard.visibleOrGone(product.collected == true) {
                    this.animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
                        .apply {
                            duration = 500L
                        }
                    this.animation?.start()
                    binding.ivCollect.gone()
                    this.postDelayed(3000L) {
                        this.gone()
                        binding.ivCollect.visible()
                    }
                    this.setOnClickListener {
                        WishlistAddBottomDialog.showAddListDialog(
                            context,
                            batchPros = arrayListOf(
                                BatchProductArrEntry(
                                    id = product.id ?: "",
                                    type = product.type,
                                    url = product.mainImg ?: ""
                                )
                            ),
                            spmPageValue = trackPage
                        )
                    }
                }
            } else {
                // 收藏或取消收藏失败，恢复UI状态
                updateCollect(product.collected)
            }
        }
    }

    // 更新收藏按钮图标
    private fun updateCollect(collected: Boolean?) {
        binding.ivCollect.setImageResource(
            if (collected == true) com.starblink.store.R.mipmap.ic_store_product_collected
            else com.starblink.store.R.mipmap.ic_store_product_collect
        )
    }
}